﻿using System;

namespace aspNetCURD.Help
{
    public class IdGenerator
    {
        // 计数器，每次调用时 数值增加 1
        private static int _counter = 0;
        // 存储上次生成 id 时使用的时间戳
        private static int _lastTimestamp = 0;
        // 静态的只读对象
        private static readonly object _lock = new object();
        public static string GetId()
        {
            // 获取当前系统启动后的毫秒数，并取余只获取最后 5 位数
            int timestamp = Environment.TickCount % 100000;
            string uniqueId;
            int testId;
            // lock锁，锁定 _lock对象，保证 _counter、_lastTimestamp的线程安全
            lock (_lock)
            {
                if (timestamp < _lastTimestamp)
                {
                    _counter = 0;
                    _lastTimestamp = timestamp;
                }
                else
                {
                    _counter++;
                }
                testId = _counter + (timestamp * 1000);
                testId = (testId % 100000);
            }
            uniqueId = DateTime.Now.ToString().Substring(0, 4) + testId.ToString().Remove(0, 1);
            return uniqueId;
        }
    }
}
